package cn.sinothk.hussars.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class PhoneUtil {

    public static ArrayList<String> hasInstalled(Context context, String[] packageNameArr) {

        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程bai序的du包信息
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
        //从pinfo中将包名字逐一取出，压入pName list中
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            pName.add(pn);
        }

        ArrayList<String> hasAppPnList = new ArrayList<>();

        for (String markPN : packageNameArr) {
            if (pName.contains(markPN)) {
                hasAppPnList.add(markPN);
            }
        }
        return hasAppPnList;//判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }

    /**
     * 获取SN
     * @return
     */
    public static String getSN() {
        String serial = "";
        //通过android.os获取sn号
        try {
            serial = android.os.Build.SERIAL;
            if (!serial.equals("")&&!serial.equals("unknown"))return serial;
        }catch (Exception e){
            serial="";
        }

        //通过反射获取sn号
        try {
            Class<?> c =Class.forName("android.os.SystemProperties");
            Method get =c.getMethod("get", String.class);
            serial = (String)get.invoke(c, "ro.serialno");
            if (!serial.equals("")&&!serial.equals("unknown"))return serial;

            //9.0及以上无法获取到sn，此方法为补充，能够获取到多数高版本手机 sn
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) serial = Build.getSerial();
        } catch (Exception e) {
            serial="";
        }
        return serial;
    }
}
